package com.chii.order.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class WebLogAspect {
    private Logger logger = LogManager.getLogger(WebLogAspect.class);
    //测试是否接入WebLogAspect
//    public WebLogAspect() {
//        System.out.println("hhhhhhhhhhhhhhhh");
//    }

    @Pointcut("execution(* com.chii.order.controller..*.*(..))")
    public void controllerAop() {
    }

    @Before("controllerAop()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        JSONObject json = requestLog();
        json.put("process", "doBefore");
        logger.info(json.toJSONString());
    }

    @AfterReturning(returning = "ret", pointcut = "controllerAop()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        JSONObject json = requestLog();
        json.put("process", "doAfterReturning");
        json.put("response", JSON.toJSON(ret));
        logger.info(json.toJSONString());
    }

    //  获取接口参数
    private JSONObject requestLog() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        JSONObject json = new JSONObject();
        json.put("URL", request.getRequestURI());
        json.put("request", request.getParameterMap());
        return json;
    }
}
